var app = angular.module('app', ['ui.router', 'ui.bootstrap']);

app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.when('', '/article/list');
  $stateProvider.state('login', {
      url: '/login',
      title: '登录',
      views: {
        main: {
          templateUrl: '/admin/template/login.html',
          controller: 'loginCtrl',
          controllerAs: 'vm'
        }
      }
    })
    .state('articleList', {
      url: '/article/list',
      title: '文章列表',
      views: {
        main: {
          templateUrl: '/admin/template/article-list.html',
          controller: 'articleListCtrl',
          controllerAs: 'vm'
        }
      }
    })
    .state('articleEdit', {
      url: '/article/edit/:id',
      title: '文章编辑',
      views: {
        main: {
          templateUrl: '/admin/template/article-edit.html',
          controller: 'articleEditCtrl',
          controllerAs: 'vm'
        }
      }
    })
    .state('categoryList', {
      url: '/category/list',
      title: '栏目列表',
      views: {
        main: {
          templateUrl: '/admin/template/category-list.html',
          controller: 'categoryListCtrl',
          controllerAs: 'vm'
        }
      }
    })
    .state('categoryEdit', {
      url: '/category/edit/:id',
      title: '栏目编辑',
      views: {
        main: {
          templateUrl: '/admin/template/category-edit.html',
          controller: 'categoryEditCtrl',
          controllerAs: 'vm'
        }
      }
    });
}]);

app.directive('ueditor', [function() {
  return {
    require: 'ngModel',
    restrict: 'A',
    scope: {
      config: '=',
      ready: '='
    },
    link: function($S, element, attr, ctrl) {
      var _NGUeditor, _updateByRender;
      _updateByRender = false;
      _NGUeditor = (function() {
        function _NGUeditor() {
          this.bindRender();
          this.initEditor();
          return;
        }

        /**
         * 初始化编辑器
         * @return {[type]} [description]
         */
        _NGUeditor.prototype.initEditor = function() {
          var _UEConfig, _editorId, _self;
          _self = this;
          if (typeof UE === 'undefined') {
            console.error("Please import the local resources of ueditor!");
            return;
          }
          _UEConfig = $S.config ? $S.config : {};
          _editorId = attr.id ? attr.id : "_editor" + (Date.now());
          element[0].id = _editorId;
          this.editor = new UE.ui.Editor(_UEConfig);
          this.editor.render(_editorId);
          return this.editor.ready(function() {
            _self.editorReady = true;
            _self.editor.addListener("contentChange", function() {
              ctrl.$setViewValue(_self.editor.getContent());
              if (!_updateByRender) {
                if (!$S.$$phase) {
                  $S.$apply();
                }
              }
              _updateByRender = false;
            });
            if (_self.modelContent && _self.modelContent.length > 0) {
              _self.setEditorContent();
            }
            if (typeof $S.ready === "function") {
              $S.ready(_self.editor);
            }
            $S.$on("$destroy", function() {
              if (!attr.id && UE.delEditor) {
                UE.delEditor(_editorId);
              }
            });
          });
        };

        _NGUeditor.prototype.setEditorContent = function(content) {
          if (content == null) {
            content = this.modelContent;
          }
          if (this.editor && this.editorReady) {
            this.editor.setContent(content);
          }
        };

        _NGUeditor.prototype.bindRender = function() {
          var _self;
          _self = this;
          ctrl.$render = function() {
            _self.modelContent = (ctrl.$isEmpty(ctrl.$viewValue) ? "" : ctrl.$viewValue);
            _updateByRender = true;
            _self.setEditorContent();
          };
        };

        return _NGUeditor;

      })();
      new _NGUeditor();
    }
  };
}]);

//模态框服务
app
  .service('dialog', ['$uibModal', function($modal) {
    //确认框模板
    this.confirmTemplate = ['<div class="modal-header">',
      '  <button type="button" class="close" ng-click="cancel()">',
      '    <span>&times;</span></button>',
      '  <h4 class="modal-title">{{title}}</h4>',
      '</div>',
      '<div class="modal-body">',
      ' <p>{{msg}}</p>',
      '</div>',
      '<div class="modal-footer">',
      '  <button class="btn btn-sm btn-success" type="button" ng-click="ok()">确定</button>',
      '  <button class="btn btn-sm btn-default" type="button" ng-click="cancel()">取消</button>',
      '</div>',
    ].join('');

    //消息框模板
    this.showmessageTemplate = ['<div class="modal-header">',
      '  <button type="button" class="close" ng-click="cancel()">',
      '    <span>&times;</span></button>',
      '  <h4 class="modal-title">{{title}}</h4>',
      '</div>',
      '<div class="modal-body">',
      ' <p>{{msg}}</p>',
      '</div>',
      '<div class="modal-footer">',
      '  <button class="btn btn-sm btn-success" type="button" ng-click="ok()">确定</button>',
      '</div>',
    ].join('');


    //显示确认/取消提示框
    this.confirm = function(op) {
      var self = this;
      var modalInstance = $modal.open({
        animation: true,
        template: op.template || self.confirmTemplate,
        controller: 'ModalCtrl',
        size: op.size || 'md',
        resolve: {
          op: op
        }
      });

      modalInstance.result.then(function() {});
    };

    //显示消息提示框
    this.showMessage = function(op) {
      var self = this;
      var modalInstance = $modal.open({
        animation: true,
        template: op.template || self.showmessageTemplate,
        controller: 'ModalCtrl',
        size: op.size || 'sm',
        resolve: {
          op: op
        }
      });

      modalInstance.result.then(function() {});
    };

  }])
  .controller('ModalCtrl', ['$scope', '$uibModalInstance', 'op',
    function($scope, $modalInstance, op) {
      $scope.title = op.title || '提示';
      $scope.msg = op.msg;
      $scope.ok = function() {
        $modalInstance.close();
        if (op.cb) {
          op.cb();
        }
      };

      $scope.cancel = function() {
        $modalInstance.dismiss();
      };
    }
  ]);

//将对象键值对转为url参数,格式为key1=value1&key2=value2
app.setUrlParam = function(obj) {
  if (typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length) {
    var str = '';
    for (var p in obj) {
      if (obj[p]) {
        str += (str.length === 0 ? '' : '&') + p + '=' + obj[p];
      }
    }
    return str;
  } else {
    return '';
  }
};
